package com.vidmt.api.modules.sys.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.service.CrudService;
import com.vidmt.api.common.cache.MyCacheManager;
import com.vidmt.api.modules.sys.dao.LocationDao;
import com.vidmt.api.modules.sys.entity.Location;
import com.vidmt.api.modules.sys.entity.User;

@Service
@Transactional(readOnly = false)
public class LocationService extends CrudService<LocationDao, Location> {
	private static final Logger log = LoggerFactory.getLogger(LocationService.class);
	private static final String CACHE_NAME = "locCache";
	private static final String PRE_UID_ = "uid_";
	// private static final String CACHE_NAME = "traceCache";
	// private static final String PRE_UID_ = "uid_";
	@Autowired
	private MyCacheManager myCacheManager;

	public Location getFromCache(Long uid) {
		return (Location) myCacheManager.get(CACHE_NAME, PRE_UID_ + uid);
	}

	public void putToCache(Location loc) {
		myCacheManager.put(CACHE_NAME, PRE_UID_ + loc.getUid(), loc);
	}

	public void saveOrUpdate(Location entity, User user) {
		dao.insertOrUpdate(entity);
		dao.saveOrUpdateNearby(entity, user);
	}

	// 涉及到locationcache，因此此处可能写入
	@Transactional(readOnly = true)
	public List<Location> listByUids(List<Long> uids) {
		List<Location> loclist = new ArrayList<>(uids.size());

		List<Long> tmpuidlist = new ArrayList<>(uids);
		for (int i = 0; i < uids.size(); i++) {
			Long uid = uids.get(i);
			Location loc = getFromCache(uid);
			if (loc != null) {
				loclist.add(loc);
				tmpuidlist.remove(uid);
			}
		}
		if (tmpuidlist.size() > 0) {
			List<Location> tmpLocList = dao.findListByUids(tmpuidlist);
			for (Location loc : tmpLocList) {
				loclist.add(loc);
			}
		}
		return loclist;
	}

	@Transactional(readOnly = true)
	@Cacheable(value = "locCache", key = "'uid_'+#uid")
	public Location findByUid(Long uid) {
		return dao.findByUid(uid);
	}

	@Transactional(readOnly = true)
	public List<Location> getNearBy(Long uid, Double lon, Double lat, Date time, Integer sex, Double distance,
			Date birthStart, Date birthEnd, Integer offset, Integer limit) {
		return dao.getNearBy(uid, lon, lat, time, distance, sex, birthStart, birthEnd, offset, limit);
	}

	public void deleteExpiredNearby(Date time) {
		dao.deleteExpiredPoints(time);
	}
}
